// subPages/business/orders/orders.js
const app = getApp();
var util =  require('../../../utils/util.js');
var loadMoreView,p = 1,num = app.globalData.pageNum,type = 'orders'
var flag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainNavList: [{nav: '社区商城'},{nav: '健康商城'},{nav:'特膳厨房'},{nav:'积分商城'}],
    currentTab: 0,
    mainCurrent: 0,
    date: '',
    isDate: false,
    downImg: '/resources/theme/down.png',
    upImg: '/resources/theme/up.png',
    status: 10,
    logisticsName: '',
    logisticsNum: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    loadMoreView = this.selectComponent("#loadMoreView")
    var navList = [{nav: '全部订单'},{nav: '已完成订单'},{nav: '未发货订单'}]
    if(app.globalData.shopType != '1' || app.globalData.shopType!= '3'){
      navList = [{nav: '全部订单'},{nav: '已完成订单'},{nav: '未接单订单'}]
    }
    that.setData({
      navList: navList,
      dateImgSrc: that.data.downImg,
      shopType: app.globalData.shopType
    })
    that.setDate()
    that.getOrderList()
  },

  //选择主导航栏
  switchMainNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;
    if (that.data.mainCurrent == cur) {
      return false;
    } else {
      that.setData({
        mainCurrent: cur,
      })
      p = 1
      that.getOrderList()
    }
  },

  //设置日期
  setDate:function(){
    let dateStart = util.setTime(new Date())
    let Y = dateStart.split('-')
    this.setData({
      dateStart: Y[0]- 3,
      dateEnd: dateStart,
    })
  },

  bindDateChange: function(e) {
    this.setData({
      isDate: true,
      date: e.detail.value,
      dateImgSrc: this.data.downImg
    })
    this.getOrderList()
  },

  bindDateCancel:function(){
    this.setData({
      dateImgSrc: this.data.downImg
    })
  },

  //选择箭头
  imgChange:function(e){
    var that = this
    if(that.data.dateImgSrc == that.data.downImg){
      that.setData({
        dateImgSrc: that.data.upImg
      })
    }
  },

  //删除标签
  delete:function(){
    this.setData({
      isDate: false,
      date: ''
    })
    this.getOrderList()
  },

  //获取订单数据数据
  getOrderList:function(){
    var that = this
    var start_time = '',end_time = ''
    if(that.data.date){
      start_time = (new Date(String(that.data.date).replace(/-/g,"/") + ' 00:00:00').getTime())/1000
      end_time = (new Date(String(that.data.date).replace(/-/g,"/") + ' 23:59:59').getTime())/1000
    }
    var typeUrl = ''
    var data = {}
    var fun
    if(that.data.shopType != '3'){
      switch (that.data.shopType) {
        case '0':
          typeUrl = 'admin_get_community_service_shop_product_order'
          fun = that.getOrderData
          data = {p: p,num: num,community_service_shop_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
        case '1':
          typeUrl = 'admin_get_user_community_shop_product_order'
          fun = that.getOrderData
          data = {p: p,num: num,shop_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
        case '2':
          typeUrl = 'admin_get_community_service_kitchen_product_order'
          fun = that.getOrderData
          data = {p: p,num: num,kitchen_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
      }
    }else{
      var mainType = app.globalData.mainType
      if(mainType == 3){
        mainType = 2
      }
      switch (that.data.mainCurrent) {
        case 0:
          typeUrl = 'admin_get_service_shop_order'
          fun = that.getOrderData
          data = {p: p,num: num,type: mainType,community_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
        case 1:
          typeUrl = 'admin_get_health_shop_order'
          fun = that.getOrderData
          data = {p: p,num: num,type: mainType,community_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
        case 2:
          typeUrl = 'admin_get_service_kitchen_order'
          fun = that.getOrderData
          data = {p: p,num: num,type: mainType,community_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
        case 3:
          typeUrl = 'get_jf_order'
          fun = that.getOrderData2
          data = {p: p,num: num,type: 1,community_id: app.globalData.shopId,status: that.data.status,start_time: start_time,end_time: end_time}
          break;
      }
    }
    console.log(data)
    util.getAjax(`${app.globalData.apiUrl}/${typeUrl}`,fun,data,that.orderDataErr)
  },

  getOrderData(res){
    var that = this
    console.log(res)
    if(res.data.list.length != 0){
      var list = []
      for(var i in res.data.list){
        res.data.list[i].all_order_num = res.data.list[i].all_order_num?res.data.list[i].all_order_num:res.data.list[i].order_num        
        res.data.list[i].all_price = res.data.list[i].all_price?res.data.list[i].all_price:res.data.list[i].order_price
        res.data.list[i].createtime = util.setTime2(res.data.list[i].createtime)
        res.data.list[i].statusTxt = util.getOrderStatus(res.data.list[i].status)
      }
      if(p == 1) {
        list = res.data.list
      } else {
        list = that.data.orderList.concat(res.data.list)
      }
      that.setData({
        orderList: list
      })
    }else{
      that.setData({
        orderList: []
      })
    }
    loadMoreView.loadMoreComplete(res.data,type)
  },

  getOrderData2(res){
    var that = this
    // console.log(res)
    if(res.data.list.length != 0){
      var list = []
      if(p == 1) {
        list = res.data.list
      } else {
        list = that.data.orderList.concat(res.data.list)
      }
      for(var i in list){
        if(list[i].time){
          list[i].time = util.setTime2(list[i].time)
        }
        list[i].statusTxt = util.getOrderStatus(list[i].status)
      }
      that.setData({
        orderList: list
      })
    }else{
      that.setData({
        orderList: []
      })
    }
    loadMoreView.loadMoreComplete(res.data,type)
  },

  //获取商品数据异常
  orderDataErr(err){
    if(p>1){
      loadMoreView.loadMoreFail()
    }else{
      util.showModal('提示','获取订单失败，请向上滑动屏幕')
      this.setData({
        isFail: true
      })
    }
  },

  loadMoreListener: function(e) {
    p += 1
    this.getOrderList()
  },

  clickLoadMore: function(e) {
    this.getOrderList()
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;      
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
        currentTab: cur
      })
      that.setNav(cur)
    }
  },

  //设置导航
  setNav:function(current){
    var status = ''
    switch (current) {
      case 0:
        status = 10
        break;
      case 1:
        status = 3
        break;
      case 2:
        status = 1
        break;
    }
    this.setData({
      status: status
    })
    this.getOrderList()
  },

  //操作按钮
  operationBtn:function(e){
    var that = this
    var type = e.currentTarget.dataset.type
    if(type == '1'){
      //立即发货
      var id = e.currentTarget.dataset.id
      var urlType = ''
      var text = ''
      switch (that.data.shopType) {
        case '0':
          util.showModelAll('提示','是否确定立即接单',function(){
            urlType = '/service_shop_fahuo';
            util.postAjax(`${app.globalData.apiUrl}${urlType}`,function(res){
              console.log(res)
              if(res.data == 1){
                util.showToast('接单成功','success',2000)
                that.getOrderList()
              }else{
                util.showToast('接单失败，请重新点击','none',2000)
              }
            },{order_id: id})
          })
          break;
        case '1':
          that.setData({
            orderId: id
          })
          var status = e.currentTarget.dataset.status
          that.deliveryAnim(status);
          break;
        case '2':
          util.showModelAll('提示','是否确定立即接单',function(){
            urlType = '/kitchen_shop_fahuo';
            util.postAjax(`${app.globalData.apiUrl}${urlType}`,function(res){
              console.log(res)
              if(res.data == 1){
                util.showToast('接单成功','success',2000)
                that.getOrderList()
              }else{
                util.showToast('接单失败，请重新点击','none',2000)
              }
            },{order_id: id})
          })
          break;
        case '3':
          that.setData({
            orderId: id
          })
          var status = e.currentTarget.dataset.status
          that.deliveryAnim(status);
          break;
      }
    }else{
      //查看订单详情      
      switch (that.data.shopType) {
        case '0':
        case '1':
        case '2':
          wx.navigateTo({
            url: '/subPages/mine/orderDetails/orderDetails?shopType='+ app.globalData.shopType + '&orderNum=' + e.currentTarget.dataset.ordernum,
          })
          break;
        case '3':
          if(that.data.mainCurrent != 3){
            //查看订单详情
            wx.navigateTo({
              url: '/subPages/mine/orderDetails/orderDetails?shopType='+ that.data.mainCurrent + '&orderNum=' + e.currentTarget.dataset.ordernum,
            })
          }else{
            wx.navigateTo({
              url: '/subPages/integral/orderDetails/orderDetails?orderNum=' + e.currentTarget.dataset.ordernum +'&isShop=' + true ,
            })
          }
          break;
      }
    }
  },


  //获取物流公司
  logisticsNameInput:function(e){
    this.setData({
      logisticsName: e.detail.value
    })
  },

  //获取物流单号
  logisticsNumInput:function(e){
    this.setData({
      logisticsNum: e.detail.value
    })
  },

  //完成按钮
  OkDeliveryBtn:function(e){
    var that = this
    if(flag){
      return
    }
    flag = true
    if(!that.data.logisticsName || !that.data.logisticsNum){
      util.showToast('请填写完整物流信息','none',2000)
      flag = false
      return;
    }
    if(that.data.orderId){
      var urlType = ''
      var data = {}
      switch (that.data.shopType) {
        case '1':
          urlType = '/health_shop_up_order';
          data = {order_id: that.data.orderId,address_order_shop: that.data.logisticsName,address_order_num: that.data.logisticsNum}
          break;
        case '3':
          urlType = '/operation_community_jf_shop_order';
          data = {id: that.data.orderId,type: 1,address_order_shop: that.data.logisticsName,address_order_num: that.data.logisticsNum}
          break;
      }
      util.postAjax(`${app.globalData.apiUrl}${urlType}`,function(res){
        console.log(res)
        if(res.data == 1){
          util.showToast('发货成功','success',2000)
          that.getOrderList()
          var currentStatus = 'complete';
          that.deliveryAnim(currentStatus);
          flag = false
        }else{
          util.showToast('发货失败，请重新点击','none',2000)
          flag = false
        }
      },data)
    }
  },
  
  //关闭按钮
  closeBtn:function(){
    var currentStatus = 'complete';
    this.deliveryAnim(currentStatus);
  },

  //动画部分
  deliveryAnim: function (currentStatus) {
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(350).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      deliveryAnim: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        deliveryAnim: animation
      })

      //完成
      if (currentStatus == "complete") {
        this.setData(
          {
            isDelivery: false,
            orderId: '',
            logisticsName: '',
            logisticsNum: '',
          }
        );
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatus == "open") {
      this.setData(
        {
          isDelivery: true,
        }
      );
    }
  },

  //回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 600) {
      this.setData({
        isTop: true
      });
    } else {
      this.setData({
        isTop: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.isFail){
      this.getOrderList()
      return
    }
    loadMoreView.loadMore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})